import { getTokenInfo } from '@/utils/storage'

export type Auth = {
  token: string
  refresh_token: string
}

export type Profile = {
  id: string
  photo: string
  name: string
  mobile: string
  gender: number
  birthday: string
  intro: string
}

export type User = {
  id: string
  name: string
  photo: string
  art_count: number
  follow_count: number
  fans_count: number
  like_count: number
}

const initState = {
  profile: {} as Profile,
  user: {} as User,
  auth: getTokenInfo(),
}

// 定义 action 类型
export type UserAction =
  | { type: 'user/saveAuth'; payload: Auth }
  | { type: 'user/clearAuth' }
  | { type: 'user/saveUser'; payload: User }
  | { type: 'user/saveProfile'; payload: Profile }
  // 利用泛型工具 Partial<> 把属性转可选，用于更新单个用户信息
  | { type: 'user/updateProfile'; payload: Partial<Profile> }

export default function userReducer(state = initState, action: UserAction) {
  switch (action.type) {
    case 'user/saveAuth':
      return { ...state, auth: action.payload }
    case 'user/clearAuth':
      return { ...state, auth: {} as Auth }
    case 'user/saveUser':
      return { ...state, user: action.payload }
    // 保存全部用户资料
    case 'user/saveProfile':
      return { ...state, profile: action.payload }
    // 更新单条用户资料
    case 'user/updateProfile':
      return { ...state, profile: { ...state.profile, ...action.payload } }
    default:
      return state
  }
}
